<?php
/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2018/6/3
 * Time: 18:31
 */

namespace app\api\service;


use think\facade\Cache;
use think\facade\Request;

class TokenService
{

    /**
     * 生成token
    */
    public static function generateToken(){
        $randString = getRandChar(32);
        return $randString;
    }

    /**
     * @return boolean true/false
    */
    public static function verifyToken($token){
        $exist = Cache::get($token);
        if($exist){
            return true;
        }
        else{
            return false;
        }
    }

    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if (!$vars) {
            throw new \Exception('非法token');
        }
        else {
            if(!is_array($vars)) {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            }
            else{
                throw new \Exception('尝试获取的Token变量并不存在');
            }
        }
    }

}